package com.css.zfzx.sjcj.modules.hddcSamplePoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.HddcSamplepointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.HddcSamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.entity.HddcSamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.service.HddcSamplepointService;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.viewobjects.HddcSamplepointPageVO;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.viewobjects.HddcSamplepointQueryParams;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.viewobjects.HddcSamplepointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 野外采样数据-采样点-点管理
 * @author zhangcong
 * @date 2020-11-28
 */
@Service
public class HddcSamplepointServiceImpl implements HddcSamplepointService {

    private final HddcSamplepointRepository hddcSamplepointRepository;
    private final HddcSamplepointNativeRepository hddcSamplepointNativeRepository;
    private final FieldSamplePointManaExcelVerifyHandler fieldSamplePointManaExcelVerifyHandler;

    @Autowired
    public HddcSamplepointServiceImpl(HddcSamplepointRepository hddcSamplepointRepository,
                                      HddcSamplepointNativeRepository hddcSamplepointNativeRepository,
                                      FieldSamplePointManaExcelVerifyHandler fieldSamplePointManaExcelVerifyHandler) {
        this.hddcSamplepointRepository = hddcSamplepointRepository;
        this.hddcSamplepointNativeRepository = hddcSamplepointNativeRepository;
        this.fieldSamplePointManaExcelVerifyHandler = fieldSamplePointManaExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcSamplepoints(HddcSamplepointQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcSamplepointPageVO> hddcSamplepointPage = this.hddcSamplepointNativeRepository.queryHddcSamplepoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcSamplepointPage);
    }


    @Override
    public HddcSamplepointEntity getHddcSamplepoint(String id) {
        return this.hddcSamplepointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcSamplepointEntity saveHddcSamplepoint(HddcSamplepointEntity hddcSamplepoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcSamplepoint.setUuid(uuid);
        hddcSamplepoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcSamplepoint.setCreateTime(now);
        hddcSamplepoint.setUpdateTime(now);
        hddcSamplepoint.setIsValid(PlatformConstants.Y);
        hddcSamplepoint.setQualityinspectionStatus(PlatformConstants.N);
        hddcSamplepoint.setExtends10(PlatformConstants.Y);
        this.hddcSamplepointRepository.save(hddcSamplepoint);
        return hddcSamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcSamplepointEntity updateHddcSamplepoint(HddcSamplepointEntity hddcSamplepoint) {
        HddcSamplepointEntity entity = hddcSamplepointRepository.findById(hddcSamplepoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcSamplepoint);
        hddcSamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcSamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcSamplepointRepository.save(hddcSamplepoint);
        return hddcSamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcSamplepoints(List<String> ids) {
        List<HddcSamplepointEntity> hddcSamplepointList = this.hddcSamplepointRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcSamplepointList) && hddcSamplepointList.size() > 0) {
            for (HddcSamplepointEntity hddcSamplepoint : hddcSamplepointList) {
                hddcSamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcSamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcSamplepoint.setIsValid(PlatformConstants.N);
                this.hddcSamplepointRepository.save(hddcSamplepoint);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcSamplepointEntity> hddcSamplepointList = this.hddcSamplepointRepository.queryHddcSamplepointsByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcSamplepointList) && hddcSamplepointList.size() > 0) {
            for (HddcSamplepointEntity hddcSamplepoint : hddcSamplepointList) {
                hddcSamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcSamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcSamplepoint.setIsValid(PlatformConstants.N);
                this.hddcSamplepointRepository.save(hddcSamplepoint);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcSamplepointEntity> hddcSamplepointList = this.hddcSamplepointRepository.queryHddcSamplepointsByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcSamplepointList) && hddcSamplepointList.size() > 0) {
            for (HddcSamplepointEntity hddcSamplepoint : hddcSamplepointList) {
                hddcSamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcSamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcSamplepoint.setIsValid(PlatformConstants.N);
                this.hddcSamplepointRepository.save(hddcSamplepoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcSamplepointQueryParams queryParams, HttpServletResponse response) {
        List<HddcSamplepointEntity> yhDisasterEntities = hddcSamplepointNativeRepository.exportYhDisasters(queryParams);
        List<HddcSamplepointVO> list = new ArrayList<>();
        for (HddcSamplepointEntity entity : yhDisasterEntities) {
            HddcSamplepointVO yhDisasterVO = new HddcSamplepointVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "采样点-点", "采样点-点",
                HddcSamplepointVO.class, "采样点-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(fieldSamplePointManaExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcSamplepointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcSamplepointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcSamplepointVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcSamplepointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcSamplepointVO> list) {
        for (HddcSamplepointVO hddcSamplepointVO : list) {
            HddcSamplepointEntity yhDisasterEntity = new HddcSamplepointEntity();
            BeanUtils.copyProperties(hddcSamplepointVO, yhDisasterEntity);
            saveHddcSamplepoint(yhDisasterEntity);
        }
    }

}
